# -*- coding: utf-8 -*-
import base64
import uuid
import random
from Crypto import Random
from Crypto.Hash import SHA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pkcs1_v1_5
from Crypto.Signature import PKCS1_v1_5 as Signature_pkcs1_v1_5
from Crypto.PublicKey import RSA
from Crypto.Hash import MD5

def gen_devid(devname):
    # dev_uuid = uuid.uuid5(uuid.NAMESPACE_DNS, devname)
    dev_id = random.randint(100000,999999)
    with open('dev_id.txt', 'w') as f:
        f.write(str(dev_id))

def gen_devkey():
    random_generator = Random.new().read
    rsa = RSA.generate(1024, random_generator)
    private_pem = rsa.exportKey()
    public_pem = rsa.publickey().exportKey()
    with open('priv_key.pem', 'w') as f:
        f.write(private_pem)
    with open('pub_key.pem', 'w') as f:
        f.write(public_pem)

def rsa_sign(data):
    private_key_file = open('priv_key.pem', 'r')
    pri_key = RSA.importKey(private_key_file.read())
    signer = PKCS1_v1_5.new(pri_key)
    hash_obj = my_hash(data)
    signature = base64.b64encode(signer.sign(hash_obj))
    private_key_file.close()
    return signature

def rsa_verify(signature, data):
    public_key_file = open('pub_key.pem', 'r')
    pub_key = RSA.importKey(public_key_file.read())
    hash_obj = my_hash(data)
    verifier = PKCS1_v1_5.new(pub_key)
    public_key_file.close()
    return verifier.verify(hash_obj, base64.b64decode(signature))


def md5_sign(data,api_key):
    if not api_key:
        public_key_file = open('pub_key.pem', 'r')
        api_key = RSA.importKey(public_key_file.read())
    md5 = MD5.new()
    md5.update((data+api_key).encode(encoding='UTF-8'))
    return md5.hexdigest()
 
def md5_verify(data,api_key,signature):
    if md5_sign(data,api_key) == signature:
        return True
    else:
        return False

if __name__ == '__main__':
    devname = "pooltable01"
    sign = md5_sign(devname,devname)
    print(sign)
    # gen_devkey()
